package com.web44.ssm.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import java.lang.reflect.Method;

/**
 * @Title: ErrorInterceptor
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/16 10:27
 * if(handler instanceof  ResourceHttpRequestHandler) {
 *             return true;
 *         }
 */
@Component
public class ErrorInterceptor  implements HandlerInterceptor {

    /**
     *
     * @param request
     * @param response
     * @param handler 保留controller 中所有的方法
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行静态资源
        if(handler  instanceof  ResourceHttpRequestHandler) {
            return true;
        }
        HandlerMethod hm = (HandlerMethod)handler;
        Method method = hm.getMethod();  // 进入到的controller 中的方法
        Class<?> beanType = hm.getBeanType(); // 进入到controller 中的类
        boolean annotationPresent = method.isAnnotationPresent(ResponseBody.class);
        boolean annotationPresent1 = beanType.isAnnotationPresent(RestController.class);
        boolean isjosn = annotationPresent || annotationPresent1;
        request.setAttribute("isjosn",isjosn);
        return true;
    }
}
